import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hao/page/user/LoginPage.dart';
import 'package:hao/utils/ColorUtil.dart';
import 'package:hao/utils/HaoModel.dart';
import 'package:hao/utils/RecordModel.dart';
import 'package:hao/utils/Utils.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:timezone/timezone.dart' as tz;
import 'AddRecordViewModel.dart';

class AddRecordPage extends StatelessWidget {
  final Record? chu;

  AddRecordPage({this.chu})
      : _viewModel = Get.put(AddRecordViewModel(chu: chu));

  final AddRecordViewModel _viewModel;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(chu == null ? "添加记录" : "修改记录"),
        actions: chu == null
            ? []
            : [
                Padding(
                  padding: const EdgeInsets.only(right: 10),
                  child: GestureDetector(
                    onTap: () {
                      showAlert("提示", "确定要删除该项？", () async {
                        Get.back();

                        SharedPreferences sharedPreferences =
                            await SharedPreferences.getInstance();
                        String str =
                            sharedPreferences.getString("list") ?? "[]";
                        List _list = json.decode(str);
                        for (int i = 0; i < _list.length; i++) {
                          Map map = _list[i];
                          int id = map["id"];
                          if (id == chu!.id) {
                            _list.removeAt(i);
                            break;
                          }
                        }

                        sharedPreferences
                            .setString("list", json.encode(_list))
                            .then((value) {
                          Get.back(result: true);
                          flutterLocalNotificationsPlugin.cancel(chu?.id ?? 0);
                        });

                        // chu!.delete().then((value) {
                        //   Get.back(result: true);
                        //   flutterLocalNotificationsPlugin.cancel(chu?.id ?? 0);
                        // });
                      });
                    },
                    child: const Icon(
                      Icons.delete_forever,
                      color: Colors.red,
                    ),
                  ),
                )
              ],
      ),
      body: ListView(
        padding: const EdgeInsets.symmetric(vertical: 20),
        children: [
          InputBgWidget(
            zuTextField(
                controller: _viewModel.titleController,
                hintText: "请输入租用物品",
                inputType: TextInputType.text),
          ),
          InputBgWidget(Row(
            children: [
              Expanded(
                  child: zuTextField(
                      controller: _viewModel.priceController,
                      hintText: "请输入金额",
                      inputType: TextInputType.number)),
              const Text("元")
            ],
          )),
          GestureDetector(
            onTap: () {
              _viewModel.chooseTime(false);
            },
            child: InputBgWidget(
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text("请选择租用时间"),
                  Container(
                    height: 48,
                    alignment: Alignment.centerLeft,
                    child: Obx(() => Text(
                          _viewModel.timeStr.value,
                        )),
                  )
                ],
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              _viewModel.chooseTime(true);
            },
            child: InputBgWidget(
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text("请选择归还时间"),
                  Container(
                    height: 48,
                    alignment: Alignment.centerLeft,
                    child: Obx(() => Text(
                          _viewModel.expireStr.value,
                        )),
                  )
                ],
              ),
            ),
          ),
          InputBgWidget(
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text("是否提醒"),
                Obx(() => Switch(
                    value: _viewModel.isRemind.value,
                    onChanged: (isRemind) {
                      _viewModel.changeRemind(isRemind);
                    }))
              ],
            ),
          ),
          InputBgWidget(SizedBox(
            height: 100,
            child: zuTextField(
                controller: _viewModel.remarkController,
                hintText: "请输入备注(可选)",
                inputType: TextInputType.text),
          )),
          const SizedBox(
            height: 20,
          ),
          LoginBgWidget("确定", () {
            _viewModel.addRecord();
          })
        ],
      ),
    );
  }

  Widget InputBgWidget(Widget child) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 40, vertical: 10),
      child: child,
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2),
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(
          color: Get.theme.primaryColor,
          boxShadow: [haoBoxShadow()],
          borderRadius: BorderRadius.circular(24)),
    );
  }
}
